package crmdna.custom.isha;
import static crmdna.common.OfyService.ofy;

import java.util.Set;

import crmdna.client.practice.Practice;
import crmdna.client.user.User;
import crmdna.client.user.User.Action;
import crmdna.client.user.User.ResourceType;
import crmdna.common.Utils;
import crmdna.crmdna.Client;

public class IshaConfig {
	private static final String ISHA = "isha";
	private static final String KEY = "KEY";
	
	public static class CustomConfigProp {
		Set<Long> sathsangPracticeIds;
	}
	
	static CustomConfigProp setSathsangPractices(Set<Long> practiceIds, String login) {
		
		Client.ensureValidClient(ISHA);
		User.ensureAccess(ISHA, login, ResourceType.CUSTOM_CONFIG, 0, Action.WRITE);
		
		if ((null == practiceIds) || (practiceIds.size() == 0))
			Utils.throwIncorrectSpecException("practiceIds is null or empty set");
		
		//validate all practices
		for (Long practiceId : practiceIds) {
			Practice.safeGet(ISHA, practiceId);
		}
		
		IshaConfigEntity entity = ofy(ISHA).load().type(IshaConfigEntity.class).id(KEY).get();
		if (null == entity) {
			entity = new IshaConfigEntity();
			entity.key = KEY;
		}
		
		entity.sathsangPracticesIds = practiceIds;
		ofy(ISHA).save().entity(entity).now();
		
		return entity.toProp();
	}
	
	static CustomConfigProp safeGet() {
		Client.ensureValidClient(ISHA);
		
		IshaConfigEntity entity = ofy(ISHA).load().type(IshaConfigEntity.class).id(KEY).get();
		if (null == entity)
			Utils.throwNotFoundException("CustomConfig not specified for client [" + ISHA + "]");			
		
		return entity.toProp();
	}
}
